<!DOCTYPE html>
<html>
<head>
    <include file="./Application/Home/View/Tpl/head.html" />
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/libs/dataTables.fixedHeader.css">
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/libs/dataTables.tableTools.css">
</head>
<body class="fixed-header theme-blue-gradient">
<div id="theme-wrapper">
    <include file="./Application/Home/View/Tpl/header.html" />


    <input type="hidden" id="iscrack" name="iscrack" value="{$iscrack}">
    <input type="hidden" id="iswz" name="iswz" value="{$iswz}">
    <input type="hidden" id="isattack" name="isattack" value="{$isattack}">
    <!-- Content Wrapper. Contains page content -->
    <div id="page-wrapper" class="container">

        <!-- Main content -->
        <div class="row">
            <include file="./Application/Home/View/Tpl/menu.html"/>


            <div id="content-wrapper">
                <div class="row">
                    <include file="./Application/Home/View/Tpl/alert.html"/>

                    <div class="col-md-12">
                        <button class="btn pull-right  btn-success btn-lg" action="" id="scanstatus" name="scanstatus">
                            扫描状态读取中... ...
                        </button>
                        <button class="btn   btn-danger btn-lg" id="clearwifi" name="clearwifi">
                            <i class="fa  fa-trash-o"></i> 清空WiFi热点列表
                        </button>
                    </div>
                </div>
                <BR>
                <div class="row">
                    <div class="col-md-12">
                        <div class="main-box clearfix">
                            <div class="table-responsive">
                                <table id="table-example" class="table table-hover"  cellspacing="0" width="100%">
                                    <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>SSID</th>
                                        <th>MAC地址</th>
                                        <th>厂家</th>
                                        <th>信道</th>
                                        <th>设备名称</th>
                                        <th>版本号</th>
                                        <th>加密方式</th>
                                        <th>距离</th>
                                        <th>捕获时间</th>
                                        <th>GPS</th>
                                    </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>

                    </div>
                </div>



                <div  draggable="true" class="main-box small-graph-box emerald-bg" id="showstatus" style="    position: fixed;bottom: 0px; right: 15px;width: 40%;z-index: 10000;opacity: 0.9">
                    <span class="value" style="font-size: 1.2em;" id="currentstatuslabel">当前任务</span>
                    <div class="progress">
                        <div style="width: 0%;" aria-valuemax="100" aria-valuemin="0" aria-valuenow="60" role="progressbar" class="progress-bar">

                        </div>
                    </div>
                    <div id="subcurrentstatuslabel">
                    <span class="subinfo" id="crackwifistatus" >  </span>
                    <span class="subinfo" id="wzwifistatus" >  </span>
                    <span class="subinfo" id="attackwifistatus" >  </span>
                    </div>
                </div>
                <include file="./Application/Home/View/Tpl/footer.html"/>

            </div>

        </div>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <div class="modal   fade" id="myApModal" tabindex="-1" role="dialog" aria-labelledby="myApModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width: 100%;margin: 0px">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myApModalLabel">WiFi热点信息</h4>
                </div>
                <div class="modal-body" id="">

                    <div class="row">
                        <div class="col-md-12">
                            <table id="detailtable" class="table table-hover" style="margin-bottom: 0px"  cellspacing="0" width="100%">
                                <thead>
                                <tr>
                                    <th>SSID</th>
                                    <th>MAC地址</th>
                                    <!--<th>信道</th>
                                    <th>设备名称</th>
                                    <th>版本号</th>-->
                                    <th>加密方式</th>
                                    <th>捕获时间</th>
                                    <!--<th>距离</th>-->
                                    <th>操作</th>

                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td id="ssid"></td>
                                    <td id="mac"></td>
                                    <!-- <td id="signalpath"></td>
                                    <td id="devmodel"></td>
                                    <td id="ver_name"></td>-->
                                    <td id="encryption"></td>
                                    <td id="timeparse"></td>
                                    <!--<td>
                                        <span class="label label-success" mac="" id="distance" class="distance"></span>
                                    </td>-->


                                    <td>
                                        <button class="btn   btn-default getapsta"
                                                apmac="" >
                                            查看接入终端
                                        </button>

                                        <button class="btn   btn-info crackwifi"  type="button" >
                                        </button>

                                        <button class="btn   btn-success wzwifi"   type="button" >
                                            开启伪装
                                        </button>

                                        <button class="btn   btn-danger attackwifi" type="button">
                                            开启攻击
                                        </button>

                                        <button class="btn   btn-info distance" id="distance" type="button">
                                            开启定位
                                        </button>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>

                        <div id="allmap" style="height:300px;width:100%;"></div>

                        <table id="stalisttable" class="table table-hover"  cellspacing="0" width="100%" style="display: none">
                            <thead>
                            <tr>
                                <th>终端MAC地址</th>
                                <th>请求链接SSID</th>
                                <th>终端名称</th>
                                <th>捕获时间</th>
                                <th>操作</th>

                            </tr>
                            </thead>
                        </table>

                        <div id="distance_map" class="col-md-12" style="display: none;padding-top: 20px">

                            <div class="label label-primary macval pull-right">实时定位启动中...</div>
                            <div class="label label-success distanceval pull-right" style="margin-right: 10px"></div>
                            <div id="locationPanel" style="width: 100%;height:400px;"></div>
                            <audio id="snd" src="" autoplay></audio >
                        </div>
                       <!-- <div class="" id="stainfotr" style="display: none;height:300px;width:100%;">

                        </div> -->
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary pull-left btn-lg" data-dismiss="modal">关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>

</div>
<!-- ./wrapper -->
<input type="hidden" id="wzwifiname" name="wzwifiname">
<include file="./Application/Home/View/Tpl/commjs.html" />
<!--<script src="__PUBLIC__/js/jquery.dataTables.js"></script>

<script src="__PUBLIC__/js/jquery.dataTables.bootstrap.js"></script>
-->
<script src="__PUBLIC__/js/alertsetting.js"></script>

<script src="__PUBLIC__/datatable/datatables.min.js"></script>
<script src="__PUBLIC__/datatable/dataTables.bootstrap.js"></script>

<link rel="stylesheet" type="text/css" href="__PUBLIC__/datatable/buttons/css/buttons.bootstrap4.min.css">
<script src="__PUBLIC__/datatable/buttons/js/dataTables.buttons.js"></script>
<script src="__PUBLIC__/datatable/buttons/js/jszip.min.js"></script>
<script src="__PUBLIC__/datatable/buttons/js/buttons.html5.min.js"></script>

<!-- highcharts-->
<script src="__PUBLIC__/plugins/highcharts/highcharts.js"></script>


<!-- <script type="text/javascript" src="../libs/js-xlsx/xlsx.core.min.js"></script> -->
<!--<script type="text/javascript" src="__PUBLIC__/js/libs/FileSaver/FileSaver.min.js"></script>
<script type="text/javascript" src="__PUBLIC__/js/tableExport.js"></script>-->

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=kaRXcPncFqA676tqP7vR6MqT4cQqQ0p7"></script>

<script type="text/javascript">
    var  map = null;
    var base = new Base64();
    $(function(){
        function getmacalert() {
            $.ajax({
                url : "{:U('/Home/scanwifi/getappearmac','',false)}",
                type : "post",
                dataType : "json",
                data: null,
                timeout:6000,
                success:function(result){
                    console.log(result);

                    if(result.status==true){
                        $("#macname").html('');
                        for(var iloop=0; iloop<result.data.length;iloop++){
                            $("#macalert").show();
                            $("#macname").append('<h4 >'+
                                '告警标识：' + result.data[iloop]['alertname'] +
                                ' | mac：' + result.data[iloop]['s_mac']+
                                ' 在' + result.data[iloop]['timedesc'] + '出现！</h4>');
                        }
                    }
                },
                error:function(msg){
                    console.log(msg);
                }
            });
        }
        setInterval(getmacalert, 10000);


        $("#currentstatuslabel").click(function () {
            if($("#showstatus").css('width')=='55px')
                $("#showstatus").css('width','40%');
            else
                $("#showstatus").css('width','55px');
            $("#subcurrentstatuslabel").toggle();
        })

        //获取当前ap是否正在破解或攻击或伪装
        $.ajax({
            url : "{:U('/Home/scanwifi/getstatus','',false)}",
            type : "post",
            dataType : "json",
            data: null,
            timeout:6000,
            success:function(result){
                console.log(result);
                if(result.status==true){
                    if(result.data.crack!=''){
                        var htmls='SSID<span class="label label-success label-large">'+result.data.crack['ssid']+'</span> | mac'+
                            '<span class="label label-success label-large">' +result.data.crack['mac']+'</span>'+ '正在破解中';
                        //htmls+='<button class="btn btn-info ">停止破解</button>';
                        $("#crackwifistatus").html(htmls);
                    }
                    else{
                        $("#crackwifistatus").html('暂无破解任务');
                    }
                    if(result.data.wz!=''){
                        var htmls='SSID<span class="label label-success  ">'+result.data.wz['ssid']+'</span> 秘钥'+
                            '<span class="label label-danger  ">' +result.data.wz['encrykey']+'</span> '+
                            '<span class="label label-default ">' +result.data.wz['encrytype']+'</span>'+ '正在伪装中';
                        //htmls+='<button class="btn btn-success  ">停止伪装</button>';
                        $("#wzwifistatus").html(htmls);
                    }else
                    {
                        $("#wzwifistatus").html('暂无伪装任务');
                    }
                    if(result.data.attack!=''){
                        var htmls='SSID<span class="label label-success label-large">'+result.data.attack['ssid']+'</span> | mac'+
                           '<span class="label label-success label-large">' +result.data.attack['mac']+'</span>'+ '正在攻击中';
                        //htmls+='<button class="btn btn-danger   ">停止攻击</button>';
                        $("#attackwifistatus").html(htmls);
                    }else{
                        $("#attackwifistatus").html('暂无攻击任务');
                    }
                }
            },
            error:function(msg){
                console.log(msg);
            }
        });

        var distanceinterval=null;
        var gpsinterval;
        var interval;
        var currentmac='';
        var firstload=true;
        var  historyPoint= new Array();
        function drawPolyline( bmap, points) {
            if (points==null  || points.length<=1 ) {
                return;
            }

            var line=new BMap.Polyline(points, {
                strokeColor : "blue",
                strokeWeight : 1,
                strokeOpacity : 1
            });
            bmap.addOverlay(line); // 画线
            line.show();
        }
        function setmap(gps) {
            if(map==null){
                console.log('map is null, reload');
                map=new BMap.Map("allmap");
            }else
            {
                if(newmap)
                {
                    historyPoint=[];
                    map.clearOverlays();
                    newmap=false;
                }
            }

            if(gps!=""){
                //map.clearOverlays();
                var lan=gps.split(' ');
                console.log(lan);
                var sContent =
                    "<h4 style='margin:0 0 5px 0;padding:0.2em 0'>设备实时位置</h4>" +
                    "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>经纬度:"+gps+"</p>" ;
                // 百度地图API功能

                //坐标转换完之后的回调函数
                var point = new BMap.Point(lan[1], lan[0]);

                translateCallback = function (data){
                    if(data.status === 0) {
                        if(historyPoint.length>=1 &&
                            historyPoint[historyPoint.length-1].lng==data.points[0].lng
                            && historyPoint[historyPoint.length-1].lat==data.points[0].lat){
                            console.log('location not change');
                            return;
                        }
                        var marker = new BMap.Marker(data.points[0]);

                        var sContent =
                            "<h4 style='margin:0 0 5px 0;padding:0.2em 0'>WiFi位置</h4>" +
                            "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>经纬度:" + gps + "</p>";
                        var infoWindow = new BMap.InfoWindow(sContent);  // 创建信息窗口对象

                        map.addOverlay(marker);
                        marker.openInfoWindow(infoWindow);

                        if(firstload){
                            map.centerAndZoom(point, 15);
                            map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
                        }
                        firstload=false;
                        historyPoint.push(data.points[0]);
                        drawPolyline(map,historyPoint);
                    }
                }

                var convertor = new BMap.Convertor();
                var pointArr = [];
                pointArr.push(point);
                convertor.translate(pointArr, 1, 5, translateCallback);



            }

        }

        function toUtf8(str) {
            var out, i, len, c;
            out = "";
            len = str.length;
            for(i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                } else if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
                } else {
                    out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
                }
            }
            return out;
        }

        var table = $('#table-example').DataTable({
            "stateSave": true,
            responsive: true,
            "deferRender": true,
            "bAutoWidth":true,
            dom: 'Bfrtip',
            "buttons": [
                {
                    'extend': 'excel',
                    'text': '导出excel',
                    'className': 'btn btn-primary',
                    'exportOptions':{
                        format: {
                            body: function ( data, row, column, node ) {
                                // Strip $ from salary column to make it numeric
                                return column === 1?
                                    toUtf8(data):
                                    data;
                            }
                        }
                    }
                }
            ],
            "ajax": {
                "url": "{:U('/Home/Scanwifi/getdata','',false)}",
                "type": "POST",
                "deferRender": true
            },
            /*"columnDefs": [
                {
                    "targets": [10],
                    "visible": false
                }
            ],*/
            "columns": [
                {"data": "id","width": "8%" },
                {"data": "ssid","width": "12%",
                "render":
                        function(data, type, row, meta) {
                            //type 的值  dispaly sort filter
                            //代表，是显示类型的时候判断值的长度是否超过8，如果是则截取
                            //这里只处理了类型是显示的，过滤和排序返回原始数据

                            return base.decode(data)+' ';
                        }
                },
                {"data": "mac"},
                {"data": "vendor"},
                {"data": "signalpath","width": "7%"},
                {"data": "devmodel","width": "9%"},
                {"data": "ver_name","width": "9%"},
                {"data": "encryption","width": "10%" },
                {"data": "distance","width": "10%" },
                {"data": "timeparse","width": "10%" },
                {"data": "gps"}
            ],
            "oLanguage": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有符合条件的热点",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 个热点",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索热点:",
                "sUrl": "",
                "sEmptyTable": "没有扫描到任何热点信息",
                "sLoadingRecords": "数据加载中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            }
        });

        $('#table-example tbody').on('click', 'tr', function () {
            clearInterval(gpsinterval);

            var data = table.row(this).data();
            console.log(data);
            var ssidval=base.decode(data['ssid']);

            $("#ssid").html(ssidval);
            $("#mac").html(data['mac']);

            $(".getapsta").attr('apmac', data['mac']);

            $(".crackwifi").attr('myid', data['id']);
            $(".crackwifi").attr('xd', data['signalpath']);
            $(".crackwifi").attr('ssid', ssidval);
            $(".crackwifi").attr('encrypt', data['encryption']);
            $(".crackwifi").attr('apmac', data['mac']);
            $(".crackwifi").attr('action', 'start');
            $(".crackwifi").attr('key', '');
            $(".crackwifi").html('开启破解');

            $(".wzwifi").attr('myid', data['id']);
            $(".wzwifi").attr('xd', data['signalpath']);
            $(".wzwifi").attr('ssid', ssidval);
            $(".wzwifi").attr('encrypt', data['encryption']);
            $(".wzwifi").attr('apmac', data['mac']);
            $(".wzwifi").attr('action', 'start');
            $(".wzwifi").attr('key', '');
            $(".wzwifi").html('开启伪装');


            $(".attackwifi").attr('myid', data['id']);
            $(".attackwifi").attr('xd', data['signalpath']);
            $(".attackwifi").attr('ssid', ssidval);
            $(".attackwifi").attr('encrypt', data['encryption']);
            $(".attackwifi").attr('apmac', data['mac']);
            $(".attackwifi").attr('action', 'start');
            $(".attackwifi").attr('key', '');
            $(".attackwifi").html('开启攻击');


            $("#encryption").html(data['encryption']);

            //$("#distance").html(data['distance'] + '<span class="glyphicon glyphicon-play"></span>');
            $(".distance").attr('mac', data['mac']);
            $(".distance").attr('ssid', ssidval);
            $(".timeparse").html(data['timeparse']);

            //获取当前ap是否正在破解或攻击或伪装
            $.ajax({
                url : "{:U('/Home/scanwifi/getstatus','',false)}",
                type : "post",
                dataType : "json",
                data: {mac:data['mac']},
                timeout:6000,
                success:function(result){
                    console.log(result);
                    if(result.status==true){
                        if(result.data.crack!=''){
                            $(".crackwifi").attr('action', 'stop');
                            $(".crackwifi").html('正在破解中...');
                        }
                        if(result.data.wz!=''){
                            $(".wzwifi").attr('action', 'stop');
                            $(".wzwifi").html('正在伪装中...');
                        }
                        if(result.data.attack!=''){
                            $(".attackwifi").attr('action', 'stop');
                            $(".attackwifi").html('正在攻击中...');
                        }
                    }
                },
                error:function(msg){
                    console.log(msg);
                }
            });


            $('#myApModal').modal('toggle');
            $(".getapsta").html('查看接入终端');
            $("#stalisttable_wrapper").hide();
            $("#stalisttable").hide();
            $("#allmap").show();
            setTimeout(1000);
            newmap=true;
            setmap(data['gps']);

            currentmac=data['mac'];
            gpsinterval=window.setInterval(getcurrentGPS, 4000);
            function getcurrentGPS() {
                if(currentmac!=''){
                    //获取当前mac最新的gps字段信息
                    $.ajax({
                        url : "{:U('/Home/scanwifi/getgpsbymac','',false)}",
                        type : "post",
                        dataType : "json",
                        data: {mac:currentmac},
                        timeout:6000,
                        success:function(result){
                            if(result.data && result.data.length>=1 && result.data[0].position!=''){
                                setmap(result.data[0].position);
                            }
                        },
                        error:function(msg){
                            console.log(msg);      //执行错误
                        }

                    });

                }
            }
        });

        $('#myApModal').on('hide.bs.modal', function () {
            clearInterval(gpsinterval);
            clearInterval(interval);
            $("#stalist").hide();
            $("#allmap").show();
        });

        var count = [],time = [];
        var mac='';

        var distancestatus=true;
        $(".distance").click(function(){
            if(distancestatus){
                $("#stalisttable_wrapper").hide();
                $("#stalisttable").hide();
                $("#allmap").hide();
                $("#distance_map").show();



                clearInterval(distanceinterval);
                mac = $(this).attr('mac');
                var ssid = $(this).attr('ssid');
                var dis=$(this);
                $('#snd').attr('src','__PUBLIC__/audio/success.mp3');
                $(this).html('停止定位');
                $('.macval').html('实时定位启动中... ...');
                $.ajax({
                    url : "{:U('/Home/scanwifi/getStrength','',false)}",
                    type : "post",
                    dataType : "json",
                    data: {action:"set", mac:mac},
                    timeout:30000,
                    success:function(result){
                    },
                    error:function(msg){
                        console.log(msg);      //执行错误
                    }
                });
                drawChart( );
                distancestatus=false;
            }else{
                clearInterval(distanceinterval);
                mac = $(this).attr('mac');
                var ssid = $(this).attr('ssid');
                var dis=$(this);
                $(this).html('开启定位');
                //$('.macval').html('实时定位已停止');
                distancestatus=true;
            }
        });

        function drawChart( ){
            Highcharts.setOptions({
                global: {
                    useUTC: false
                }
            });
            function activeLastPointToolip(chart) {
                var points = chart.series[0].points;
                chart.tooltip.refresh(points[points.length -1]);
            }
            var chart = Highcharts.chart('locationPanel', {
                chart: {
                    type: 'spline',
                    marginRight: 10,
                    events: {
                        load: function () {
                            var series = this.series[0],
                                    chart = this;
                            activeLastPointToolip(chart);
                            distanceinterval=setInterval(function () {
                                $.ajax({
                                    url : "{:U('/Home/scanwifi/getStrength','',false)}",
                                    type : "post",
                                    dataType : "json",
                                    data: {action:"get", mac:mac},
                                    timeout:30000,
                                    success:function(result){
                                        console.log(result);
                                        if(result.signalstrength){
                                            var sl=parseInt(result.signalstrength);
                                            var distance=Math.round(Math.pow (10,Math.abs( sl) /(10*4))*10/100);
                                            var strength=result.signalstrength;
                                            if(sl==66){
                                                strength=0;
                                                distance=0;
                                                $('.distanceval').html(' 目标消失');
                                            }else if(distance>30){
                                                distance=30;
                                            }else{
                                                $('#snd').attr('src','__PUBLIC__/audio/'+distance+'.mp3');
                                                $('.distanceval').html(' 距离：'+distance+'米');
                                            }
                                            $('.macval').html('场强：'+strength);


                                            var x = (new Date()).getTime(), // 当前时间
                                                    y = distance;          // 随机值
                                            series.addPoint([x, y], true, false);
                                            activeLastPointToolip(chart);
                                        }
                                    },
                                    error:function(msg){
                                        console.log(msg);      //执行错误
                                    }
                                });


                            }, 5000);
                        }
                    }
                },
                title: {
                    text: ''
                },
                xAxis: {
                    type: 'datetime',
                    tickPixelInterval: 100
                },
                yAxis: {
                    title: {
                        text: null
                    }
                },
                tooltip: {
                    formatter: function () {
                        return '<b>' + this.series.name + '</b><br/>' +
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                        Highcharts.numberFormat(this.y, 2);
                    }
                },
                legend: {
                    enabled: false
                },
                series: [{
                    name: ' ',
                    data: (function () {
                        // 生成随机值
                        var data = [],
                                time = (new Date()).getTime();
                        data.push({
                            x: time + 1000,
                            y: 0
                        });
                        return data;
                    }())
                }]
            });
        }

        $(".getapsta").click(function(){
            if($("#stalisttable_wrapper").is(":visible") ){
                $(".getapsta").html('查看接入终端');
                $("#stalisttable_wrapper").hide();
                $("#stalisttable").hide();

                $("#distance_map").hide();
                clearInterval(distanceinterval);
                $('.distance').html('开启定位');

                $("#allmap").show();
            }else{
                $(".getapsta").html('查看位置');
                $("#stalisttable_wrapper").show();
                $("#stalisttable").show();
                $("#distance_map").hide();
                clearInterval(distanceinterval);
                $('.distance').html('开启定位');

                $("#allmap").hide();
                var apmac = $(this).attr('apmac');
               // $("#stainfotr").html('');

                $.ajax({
                    url : "{:U('/Home/scanwifi/getdevlist','',false)}",
                    type : "post",
                    dataType : "json",
                    data: {apmac:apmac},
                    timeout:30000,
                    success:function(result){
                        console.log(result);
                        if(result.status){
                            //将数据填充进datatable


                            var ss=$('#stalisttable').DataTable({
                                responsive: true,
                                destroy:true,
                                "data":result.data,

                                "columnDefs": [ {
                                        "targets": 0,
                                        "data": "smac"
                                    },
                                    {
                                        "targets": 1,
                                        "data": "requsetSSID"
                                    },
                                    {
                                        "targets": 2,
                                        "data": "devName"
                                    },
                                    {
                                        "targets": 3,
                                        "data": "time"
                                    },
                                    {
                                        "targets": 4,
                                        "data": function ( row, type, val, meta ) {
                                            var apmac=" apmac="+row.dmac;
                                            var stamac=" stamac="+row.smac;
                                            var channel=" signalPath="+row.signalPath;
                                            var action=" action=start";
                                            return "<button class='btn btn-primary yazhi'"+apmac+stamac+channel+action+">压制</button>";
                                        }
                                    }],
                                "oLanguage": {
                                    "sProcessing": "处理中...",
                                    "sLengthMenu": "显示 _MENU_ 项结果",
                                    "sZeroRecords": "没有符合条件的终端",
                                    "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 个终端",
                                    "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                                    "sInfoPostFix": "",
                                    "sSearch": "搜索接入终端:",
                                    "sUrl": "",
                                    "sEmptyTable": "没有任何终端信息",
                                    "sLoadingRecords": "数据加载中...",
                                    "sInfoThousands": ",",
                                    "oPaginate": {
                                        "sFirst": "首页",
                                        "sPrevious": "上页",
                                        "sNext": "下页",
                                        "sLast": "末页"
                                    },
                                    "oAria": {
                                        "sSortAscending": ": 以升序排列此列",
                                        "sSortDescending": ": 以降序排列此列"
                                    },
                                    "fnDrawCallback": function ( oSettings ) {


                                    }
                                }
                            });
                            $('.yazhi').click(function () {
                                $btn=$(this);
                                var apmac=$(this).attr('apmac');
                                var srcmac=$(this).attr('stamac');
                                var action=$(this).attr('action');
                                var signalPath=$(this).attr('signalPath');
                                if(action=='start'){
                                    //开始压制
                                    $(this).html('压制开启中...');
                                }else{
                                    //停止压制
                                    $(this).html('压制停止中...');
                                }
                                /* STAAttackAct(action,signalPath,apmac,srcmac) */
                                $.ajax({
                                    url : "{:U('/Home/Scanwifi/yazhi','',false)}",
                                    type : "post",
                                    dataType : "json",
                                    data: {action:action,signalPath:signalPath, apmac:apmac, srcmac:srcmac},
                                    timeout:6000,
                                    success:function(result){
                                        if(result.status ){
                                            if(action=='start'){
                                                $btn.html('压制中...');
                                                $btn.attr('action','stop');
                                            }else{
                                                $btn.html('压制');
                                                $btn.attr('action','start');
                                            }
                                        }
                                        else{
                                            alert('压制开启失败，终端当前没有连接对应的AP。');
                                        }
                                    },
                                    error:function(msg){
                                        console.log(msg);      //执行错误

                                    }
                                });
                            });
                        }
                        else {
                        }
                    },
                    error:function(msg){
                        console.log(msg);      //执行错误
                    }

                });
            }

        });

    });

    $(".crackwifi").click(function(){
        var btn=$(this);
        var id = $(this).attr('myid');
        var xd = $(this).attr('xd');
        var ssid = $(this).attr('ssid');
        var encrypt = $(this).attr('encrypt');
        var apmac = $(this).attr('apmac');
        var action=$(this).attr('action');
        var key=$(this).attr('key');

        if($("#showstatus").css('width')=='55px'){
            $("#showstatus").css('width','40%');
            $("#subcurrentstatuslabel").show();
        }
        var htmls='SSID<span class="label label-success label-large">'+ssid+'</span> | mac'+
            '<span class="label label-success label-large">' +apmac+'</span>';
        if(action=='start'){
            btn.html('破解中... ...');

            $("#crackwifistatus").html(htmls+'破解中... ...');
        }else{
            btn.html('破解停止中... ...');
            $("#crackwifistatus").html(htmls+'破解停止中... ...');
        }

        $(this).attr('action', $(this).attr('action')=='start'?'stop':'start');

        var intervalcrack;
        $.ajax({
            url : "{:U('/Home/scanwifi/crackWiFi','',false)}",
            type : "post",
            dataType : "json",
            data: {id:id, xd: xd,ssid:ssid, encrypt:encrypt, key:key, apmac:apmac,action:action},
            timeout:30000,
            success:function(result){
                console.log(result);
                if(action=='start'){
                    btn.html('破解开启中... ...');
                    $("#crackwifistatus").html(htmls+'破解开启中... ...');
                    if(typeof(result.status) != "undefined" && result.status){
                        btn.html('破解进行中... ...');;
                        $("#crackwifistatus").html(htmls+'破解进行中... ...');
                        //定时任务获取破解结果
                        var iloop=0;
                        clearInterval(intervalcrack);
                        intervalcrack=window.setInterval(getcrackstatus, 2000);
                        function getcrackstatus( )
                        {
                            iloop++;
                            if(iloop>=1){
                                iloop=0;
                                btn.html('破解进行中... ...');
                                $("#crackwifistatus").html(htmls+'破解进行中...');
                            }
                            else{
                                btn.html('破解进行中... ');
                                $("#crackwifistatus").html(htmls+'破解进行中... ...');
                            }

                            $.ajax({
                                url : "{:U('/Home/scanwifi/getcrackWiFiStatus','',false)}",
                                type : "post",
                                dataType : "json",
                                data: {id:id, xd: xd,ssid:ssid, encrypt:encrypt, key:key, apmac:apmac,action:action},
                                timeout:30000,
                                success:function(result){
                                    console.log(result);
                                    if(result.status=='run'){

                                    }else if(result.status=='fail'){
                                        alert('破解失败：'+result.reason);
                                        $("#crackwifistatus").html(htmls+'破解失败：'+result.reason);

                                        btn.html('开启破解 ');
                                        btn.attr('action','start');
                                        clearInterval(intervalcrack);
                                    }else{
                                        alert('破解成功！密码：'+result.secret);
                                        $("#crackwifistatus").html(htmls+'破解成功！密码'+result.secret);
                                        btn.html('开启破解 ');
                                        btn.attr('action','start');
                                        $("#crackpwdval"+id).val(result.secret);
                                        $("#crackpwd"+id).html('(<small class=" ">密码：'+ result.secret +'</small>)');
                                        clearInterval(intervalcrack);
                                    }

                                },
                                error:function(msg){
                                    console.log(msg);      //执行错误
                                    btn.attr('action', 'start');
                                    $("#crackwifistatus").html('['+apmac+']破解失败');
                                    if(action=='stop'){
                                        btn.html('开启破解');
                                    }else{
                                        btn.html('停止破解');
                                    }
                                }
                            });
                        }

                    }else {
                        alert('破解失败：'+result.reason);
                        $("#crackwifistatus").html('['+apmac+']破解失败：'+result.reason);
                        btn.html('开启破解');
                        btn.attr('action','start');
                        $("#iscrack").val(0);
                    }
                }else{
                    btn.html('开启破解');
                    $("#crackwifistatus").html('暂无破解任务');
                    $("#iscrack").val(0);
                }

            },
            error:function(msg){
                console.log(msg);      //执行错误
                $("#crackwifistatus").html('');
                $(this).attr('action', 'start');
                if(action=='start'){
                    btn.html('开启破解');
                }else{
                    btn.html('停止破解');
                }
            }

        });
    });


    $(".attackwifi").click(function(){
        var btn=$(this);
        var id = $(this).attr('myid');
        var xd = $(this).attr('xd');
        var ssid = $(this).attr('ssid');
        var encrypt = $(this).attr('encrypt');
        var apmac = $(this).attr('apmac');
        var action=$(this).attr('action');
        var key=$(this).attr('key');

        if($("#showstatus").css('width')=='55px'){
            $("#showstatus").css('width','40%');
            $("#subcurrentstatuslabel").show();
        }
        var htmls='SSID<span class="label label-success label-large">'+ssid+'</span> | mac'+
            '<span class="label label-success label-large">' +apmac+'</span>';
        if(action=='start'){
            btn.html('攻击启动中');
            $("#attackwifistatus").html(htmls+'攻击启动中');
        }else{
            btn.html('攻击停止中');
            $("#attackwifistatus").html(htmls+'攻击停止中...');
        }

        $(this).attr('action', $(this).attr('action')=='start'?'stop':'start');

        $.ajax({
            url : "{:U('/Home/scanwifi/attackWiFi','',false)}",
            type : "post",
            dataType : "json",
            data: {id:id, xd: xd,ssid:ssid, encrypt:encrypt, key:key, apmac:apmac,action:action},
            timeout:30000,
            success:function(result){
                console.log(result);

                if(action=='start'){
                    btn.html('正在攻击中...');
                    $("#attackwifistatus").html(htmls+'正在攻击中...');
                }else{
                    $("#attackwifistatus").html('暂无攻击任务');
                    btn.html('开启攻击');
                }
            },
            error:function(msg){
                $("#attackwifistatus").html('暂无攻击任务');
                console.log(msg);      //执行错误
                if(action=='start'){
                    btn.html('开启攻击');
                }else{
                    btn.html('停止攻击');
                }
            }

        });
    });
    //xd="{$vo['signalPath']}" ssid="{$vo['ssid']}" encrypt="{$vo['encryption']}" key="" apmac="{$vo['mac']}"

    $(".wzwifi").click(function(){
        $(this).attr("disabled","true");

        var btn=$(this);
        var id = $(this).attr('myid');
        var xd = $(this).attr('xd');
        var ssid = $(this).attr('ssid');
        var encrypt = $(this).attr('encrypt');
        var apmac = $(this).attr('apmac');
        var action=$(this).attr('action');
        var key=$(this).attr('key');

        var key = $("#crackpwdval"+id).val()?$("#crackpwdval"+id).val():"12345678";

        if($("#showstatus").css('width')=='55px'){
            $("#showstatus").css('width','40%');
            $("#subcurrentstatuslabel").show();
        }

        var htmls='SSID<span class="label label-success label-large">'+ssid+'</span> 秘钥'+
            '<span class="label label-success label-large">' +key+'</span>'+
            '<span class="label label-default ">' +encrypt+'</span>';
        if(action=='start'){
            $("#wzwifistatus").html(htmls+'伪装启动中');
            btn.html('伪装启动中');

        }else{
            btn.html('伪装停止中');
            $("#wzwifistatus").html(htmls+'伪装停止中');
        }
        $("#iswz").val($("#iswz").val()==0?1:0);
        $(this).attr('action', $(this).attr('action')=='start'?'stop':'start');



        $.ajax({
            url : "{:U('/Home/scanwifi/WZWifi','',false)}",
            type : "post",
            dataType : "json",
            data: {id:id, xd: xd,ssid:ssid, encrypt:encrypt, key:key, apmac:apmac,action:action},
            timeout:30000,
            success:function(result){
                console.log(result);

                if(action=='start'){
                    btn.html('正在伪装中');
                    $("#wzwifistatus").html(htmls+'正在伪装中');
                }else{
                    btn.html('开启伪装');
                    $("#wzwifistatus").html('暂无伪装任务');
                }
                btn.removeAttr("disabled");
            },
            error:function(msg){
                console.log(msg);      //执行错误
                $("#wzwifistatus").html('暂无伪装任务');
                if(action=='start'){
                    btn.html('开启伪装');
                }else{
                    btn.html('停止伪装');
                }
                btn.removeAttr("disabled");
            }

        });
    });

    function getscanstatus(){
        $.ajax({
            url : "{:U('/Home/scanwifi/getscanstatus','',false)}",
            type : "post",
            dataType : "json",
            data: null,
            timeout:6000,
            success:function(result){
                if(result.scanstatus=="runing"){
                    $("#scanstatus").attr('action','stop');
                    $("#scanstatus").html('停止扫描');
                    $("#scanstatus").attr('class','btn pull-right  btn-success btn-lg');
                }
                else{
                    $("#scanstatus").attr('action','start');
                    $("#scanstatus").html('开启扫描');
                    $("#scanstatus").attr('class','btn pull-right  btn-primary btn-lg');
                }
            },
            error:function(msg){
                console.log(msg);      //执行错误
                $("#scanstatus").attr('action','start');
                $("#scanstatus").html('扫描组件状态未知');
            }

        });
    }
    getscanstatus();


    $('#scanstatus').click(function () {
        var action=$(this).attr('action');
        $.ajax({
            url : "{:U('/Home/scanwifi/doscan','',false)}",
            type : "post",
            dataType : "json",
            data: {action:action},
            timeout:6000,
            success:function(result){
                if(result.status=="stop"){
                    $("#scanstatus").attr('action','stop');
                    $("#scanstatus").html('停止扫描');
                    $("#scanstatus").attr('class','btn pull-right  btn-success btn-lg');
                }
                else{
                    $("#scanstatus").attr('action','start');
                    $("#scanstatus").html('开启扫描');
                    $("#scanstatus").attr('class','btn pull-right  btn-primary btn-lg');
                }

            },
            error:function(msg){
                console.log(msg);      //执行错误
                $("#scanstatus").attr('action','start');
                $("#scanstatus").html('扫描组件状态未知');
            }

        });
    });

    $("#clearwifi").click(function(){
        $.ajax({
            url : "{:U('/Home/scanwifi/DatabaseClearAP','',false)}",
            type : "post",
            dataType : "json",
            data: null,
            timeout:6000,
            success:function(result){
                console.log(result);
                $("#wifilist").remove();
                $('#table-example').dataTable().fnClearTable();
            },
            error:function(msg){
                console.log(msg);      //执行错误
                alert("系统错误!");
            }
        });

    });

    $("#clearsta").click(function(){
        $.ajax({
            url : "{:U('/Home/scanwifi/DatabaseClearSTA','',false)}",
            type : "post",
            dataType : "json",
            data: null,
            timeout:6000,
            success:function(result){
                console.log(result);
                $("#stalist").remove();
            },
            error:function(msg){
                console.log(msg);      //执行错误
                alert("系统错误!");
            }
        });
    });


</script>

</body>
</html>


